package com.chuangjiangx.member.manager.web.web.score.controller;

import com.chuangjiangx.commons.page.PagingResult;
import com.chuangjiangx.commons.response.Response;
import com.chuangjiangx.commons.response.ResponseUtils;
import com.chuangjiangx.member.basic.ddd.domain.model.ClaimStatus;
import com.chuangjiangx.member.manager.basic.web.controller.BaseController;
import com.chuangjiangx.member.manager.basic.web.interceptor.Login;
import com.chuangjiangx.member.manager.common.Constants;
import com.chuangjiangx.member.manager.common.RequestHeadersUtil;
import com.chuangjiangx.member.manager.common.ThreadLocalUser;
import com.chuangjiangx.member.manager.common.utils.StrUtils;
import com.chuangjiangx.member.manager.web.web.score.request.QueryScoreGiftRecordRequest;
import com.chuangjiangx.member.score.ddd.dal.condition.QueryScoreGiftRecordCondition;
import com.chuangjiangx.member.score.ddd.dal.dto.ScoreGiftRecordList;
import com.chuangjiangx.member.score.ddd.query.MbrScoreGiftRecordQuery;
import com.sun.jmx.snmp.ThreadContext;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

/**
 * @author cj-ch
 * @date 2018/7/2 下午6:13
 */
@RestController
@RequestMapping(value = "/api/mbr/score-gift-record",produces = MediaType.APPLICATION_JSON_VALUE)
public class MbrScoreGiftRecordController extends BaseController {
    @Autowired
    private MbrScoreGiftRecordQuery mbrScoreGiftRecordQuery;


    @RequestMapping(value = "/search-list")
    @Login
    public Response searchList(
            HttpSession session,
            QueryScoreGiftRecordRequest request
    ){
        ThreadLocalUser user = (ThreadLocalUser) ThreadContext.get(Constants.CURRENT_LOGIN_USER_KEY);
        QueryScoreGiftRecordCondition condition = new QueryScoreGiftRecordCondition();
        condition.setMerchantId(user.getMerchantId());
        condition.setStartTime(request.getStartTime());
        condition.setEndTime(request.getEndTime());
        condition.setMobile(request.getMobile());
        condition.setPageNumber(request.getPage().getPageNO());
        condition.setPageSize(request.getPage().getEveryPageCount());

        setStoreCondition(user,condition);

        PagingResult<ScoreGiftRecordList> page = mbrScoreGiftRecordQuery.findMbrScoreGiftRecordList(condition);
        page.getItems()
                .forEach(s -> {
                    s.setMobile(StrUtils.encodeMobilePhone(s.getMobile()));
                });
        return ResponseUtils.successCamel(page);
    }

    private void setStoreCondition(ThreadLocalUser user, QueryScoreGiftRecordCondition condition) {
        if(1 == user.getUserType()){
            condition.setStoreId(user.getStoreId());
        } else if(2 == user.getUserType()){
            condition.setStoreUserId(user.getStoreUserId());
        }
    }



    /**
     * 积分兑换记录 导出
     */
    @RequestMapping(value = "/export/score-gift-record-list", produces = "application/json")
    public void exportScoreGiftRecordList(HttpServletResponse response, HttpServletRequest request, HttpSession session) throws IOException, ParseException {

        ThreadLocalUser user = (ThreadLocalUser) ThreadContext.get(Constants.CURRENT_LOGIN_USER_KEY);
        //封装获取参数
        QueryScoreGiftRecordCondition condition = new QueryScoreGiftRecordCondition();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String startTime = request.getParameter("startTime");
        String endTime = request.getParameter("endTime");
        condition.setMobile(request.getParameter("mobile"));
        if(!StringUtils.isEmpty(request.getParameter("storeId"))){
            condition.setStoreId(Long.valueOf(request.getParameter("storeId")));
        }
        if(!StringUtils.isEmpty(startTime)){
            condition.setStartTime(sdf.parse(startTime));
        }
        if(!StringUtils.isEmpty(endTime)){
            condition.setEndTime(sdf.parse(endTime));
        }
        condition.setMerchantId(user.getMerchantId());
        condition.setPageNumber(Integer.valueOf(request.getParameter("pageNO")));
        condition.setPageSize(EXPORT_SIZE);

        //生成模板
        OutputStream out = response.getOutputStream();
        RequestHeadersUtil.exportRequestHeader(response, "积分兑换记录");

        OutputStreamWriter osw = null;
        BufferedWriter bw = null;
        try {
            PagingResult<ScoreGiftRecordList> result = mbrScoreGiftRecordQuery.findMbrScoreGiftRecordList(condition);
            List<ScoreGiftRecordList> scoreGiftRecordList = result.getItems();
            scoreGiftRecordList.forEach(scoreGiftRecord -> {
                if (StringUtils.isNotBlank(scoreGiftRecord.getMobile())) {
                    scoreGiftRecord.setMobile(StrUtils.encodeMobilePhone(scoreGiftRecord.getMobile()));
                }
            });

            osw = new OutputStreamWriter(out, "GBK");
            bw = new BufferedWriter(osw);
            bw.append("序号").append(",")
                    .append("兑换时间").append(",")
                    .append("兑换商品").append(",")
                    .append("消耗积分").append(",")
                    .append("提货码").append(",")
                    .append("手机号").append(",")
                    .append("可用积分").append(",")
                    .append("使用状态").append(",")
                    .append("操作人").append(",")
                    .append("\r");
            if (!scoreGiftRecordList.isEmpty()) {
                int myOrderListSize = scoreGiftRecordList.size();
                for(int item = 0;item < myOrderListSize;item ++){
                    ScoreGiftRecordList record = scoreGiftRecordList.get(item);
                    bw.append(String.valueOf( item + 1)).append(",")
                            .append((record.getClaimTime()!=null)?sdf.format(record.getClaimTime()):"").append(",")
                            .append(StringUtils.isEmpty(record.getGoodsName())?"":record.getGoodsName()).append(",")
                            .append(String.valueOf(record.getScore())).append(",")
                            .append((StringUtils.isEmpty(record.getClaimCode()))?"":record.getClaimCode()).append(",")
                            .append((StringUtils.isEmpty(record.getMobile())?"":record.getMobile()).toString()).append(",")
                            .append(StringUtils.isEmpty(String.valueOf(record.getAvailableScore()))?"":String.valueOf(record.getAvailableScore())).append(",")
                            .append(ClaimStatus.getStatus(record.getClaimStatus()).name).append(",")
                            .append(StringUtils.isEmpty(record.getOperator())?"":record.getOperator()).append(",")
                            .append("\r");


                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bw != null) {
                bw.close();
            }
            if (osw != null) {
                osw.close();
            }
            if (out != null) {
                out.close();
            }
        }

    }






}
